package com.ricchieri.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.dao.interf.ICharterExpenseDao;
import com.ricchieri.filter.CharterExpenseFilter;
import com.ricchieri.model.CharterExpense;
import com.ricchieri.util.DateUtil;
import com.ricchieri.util.StringUtils;

public class CharterExpenseDao extends GenericDao implements ICharterExpenseDao {
	private static final long serialVersionUID = 3423459329621006995L;

	@Override
	@SuppressWarnings("unchecked")
	public List<CharterExpense> getAllCharterExpense(CharterExpenseFilter charterFilter) {
		Criteria criteria = criteriaAllCharters(charterFilter);
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CharterExpense> getAllCharterExpensePaginatedByFilter(
			CharterExpenseFilter charterFilter, int startRecord) {
		Criteria criteria = criteriaAllCharters(charterFilter);
		criteria.setMaxResults(BusinessSettings.ROW_MAX_RESULT);
		criteria.setFirstResult(startRecord);
		
		return criteria.list();
	}

	@Override
	public int getAllCharterExpenseCountByFilter(CharterExpenseFilter charterFilter) {
		Criteria criteria = criteriaAllCharters(charterFilter);
		Long result = (Long)criteria.setProjection(Projections.rowCount()).uniqueResult();
		return new Integer(result.intValue());
	}
	
	private Criteria criteriaAllCharters(CharterExpenseFilter charter) {
		Criteria criteria = super.criteriaAllBasic(charter, CharterExpense.class);
		
		if (charter.getStart() != null) {
			criteria.add(Restrictions.ge(getTableName().concat(".date"), DateUtil.changeToStartDay(charter.getStart())));
		}
		
		if(charter.getFinish() != null) {
			criteria.add(Restrictions.le(getTableName().concat(".date"), DateUtil.changeToEndDay(charter.getFinish())));
		}
		
		if (!StringUtils.isEmpty(charter.getCharterExpenseType())) {
			criteria.createAlias(getTableName().concat(".charterExpenseType"), "charterExpenseType");
			criteria.add(Restrictions.eq("charterExpenseType.id", charter.getCharterExpenseTypeId()));
		}
		
		if (!StringUtils.isEmpty(charter.getCharterNumber())) {
			criteria.createAlias(getTableName().concat(".charter"), "charter");
			criteria.add(Restrictions.eq("charter.charterNumber", charter.getCharteNumberInt()));
		}
		
		if (charter.getCharterId() >0) {
			criteria.createAlias(getTableName().concat(".charter"), "charter");
			criteria.add(Restrictions.eq("charter.id", charter.getCharterId()));
		}
		
		return criteria;
	}

	@Override
	protected String getTableName() {
		return "charterExpense";
	}
}
